package com.usian.service.impl;

import com.usian.mapper.TbUserMapper;
import com.usian.pojo.TbUser;
import com.usian.pojo.TbUserExample;
import com.usian.redis.RedisClient;
import com.usian.service.SSOService;
import com.usian.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class SSOServiceImpl implements SSOService {
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private RedisClient redisClient;

    @Override
    public boolean checkUserInfo(String checkValue, Integer checkFlag) {
        TbUserExample tbUserExample = new TbUserExample();
        TbUserExample.Criteria criteria = tbUserExample.createCriteria();
        if (checkFlag==1){
            criteria.andUsernameEqualTo(checkValue);

        }else if (checkFlag==2){
            criteria.andPhoneEqualTo(checkValue);

        }
        List<TbUser> list = tbUserMapper.selectByExample(tbUserExample);
        if (list==null||list.size()==0){
            return true;

        }
        return false;
    }

    @Override
    public int userRegister(TbUser tbUser) {

        String password = MD5Utils.digest(tbUser.getPassword());
        tbUser.setPassword(password);
        Date date = new Date();
        tbUser.setCreated(date);
        tbUser.setUpdated(date);
        return tbUserMapper.insert(tbUser);


    }

    @Override
    public Map userLogin(String username, String password) {
        String digest = MD5Utils.digest(password);
        TbUserExample tbUserExample=new TbUserExample();
        TbUserExample.Criteria criteria = tbUserExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andPasswordEqualTo(digest);
        List<TbUser> list = tbUserMapper.selectByExample(tbUserExample);
        if (list==null||list.size()==0){
            return null;
        }
        TbUser tbUser = list.get(0);
        String s = UUID.randomUUID().toString();
        Map<String,String> map = new HashMap<String,String>();
        map.put("token",s);
        map.put("userid", tbUser.getId().toString());
        map.put("username",username);
        tbUser.setPassword(null);
        redisClient.set("USER_INFO"+":"+s,tbUser);
        redisClient.expire("USER_INFO"+":"+s,1800);
        return map;

    }

    @Override
    public Boolean logOut(String token) {
        return redisClient.del("USER_INFO"+":"+token);
    }

    @Override
    public TbUser getUserBYToken(String token) {
        TbUser tbUser =(TbUser) redisClient.get("USER_INFO" + ":" + token);
        if (tbUser!=null){
            redisClient.expire("USER_INFO"+":"+token,1800);
            return tbUser;
        }
        return null;
    }
}
